package com.infisight.hudprojector.fragment;

import java.util.List;

import android.R.integer;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.infisight.hudprojector.R;
import com.infisight.hudprojector.data.DataMusicClass;
import com.infisight.hudprojector.data.SpeechVoiceData;
import com.infisight.hudprojector.data.VoiceDataClass;
import com.infisight.hudprojector.service.MusicService;
import com.infisight.hudprojector.util.CommonUtil;
import com.infisight.hudprojector.util.Constants;
import com.infisight.hudprojector.util.LrcView;
import com.infisight.hudprojector.util.MusicList;

/**
 * 项目名称 : FRMusic2
 * 
 * @author 作者 : fengrui
 * @date 创建时间：2015年8月18日 下午4:28:40
 * @version 1.0
 */
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MusicPlayFragment extends Fragment {
	public static final String TAG = "MusicPlayFragment";
	// 音乐名
	private TextView tv_music_name;
	// 歌手
	private TextView tv_music_singer;
	// 上一曲
	private ImageView iv_music_last;
	// 暂停和播放
	public static ImageView iv_music_play;
	// 下一曲
	private ImageView iv_music_next;
	// 歌词
	public static LrcView lrcView;
	// 音乐的播放时间
	private TextView tv_music_start_time;
	// 音乐的结束时间
	private TextView tv_music_end_time;
	// 音乐播放的进度条
	private SeekBar seekBar;
	// 音乐播放模式
	private ImageView iv_music_play_model;
	public static Boolean isLoop = true;
	private List<DataMusicClass> lists;
	private boolean isPlaying = false;
	private int choosedMusicId = 1;
	private String listTypeMusic = null;
	private int currentId = -1;
	private Boolean replaying = false;
	private MyCompletionListner myCompletionListner;
	private MyProgressBroadCastReceiver receiver;
	// 播放模式: 1.随机播放 2.顺序播放 3.单曲循环
	public static int model = 1;

	Gson gson = null;

	/**
	 * 创造唯一实例
	 * 
	 * @param musicPlayInfo
	 * @return
	 */
	@SuppressLint("NewApi")
	public static MusicPlayFragment newInstance(String musicPlayInfo) {
		MusicPlayFragment fragment = new MusicPlayFragment();
		Bundle args = new Bundle();
		args.putString("musicPlayInfo", musicPlayInfo);
		fragment.setArguments(args);
		return fragment;
	}

	/**
	 * 构造函数
	 */
	public MusicPlayFragment() {

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		init();
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.music_play_fragment, container, false);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
	}

	BroadcastReceiver musicPlayReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			gson = new Gson();
			final String action = intent.getAction();
			SpeechVoiceData svd;
			VoiceDataClass vdc;
			if (Constants.MAIN_MUSIC_ACTION.equals(action)
					|| Constants.COMMON_UTIL_ACTION.equals(action)) {
				svd = gson.fromJson(intent.getStringExtra(action),
						SpeechVoiceData.class);
				vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);
				Intent intent2 = new Intent(getActivity(), MusicService.class);
				// 暂停
				if (vdc.getType().equals(Constants.F_R_MUSIC_PAUSE_PLAY[0])) {

					intent2.putExtra("play", "pause");
					intent2.putExtra("id", choosedMusicId);
					getActivity().startService(intent2);
					isPlaying = false;
					iv_music_play.setImageResource(R.drawable.play1);
					replaying = false;
				}
				// 继续播放
				else if (vdc.getType().equals(
						Constants.F_R_MUSIC_CONTINUE_PLAY[0])) {
					intent2.putExtra("play", "playing");
					intent2.putExtra("id", choosedMusicId);
					getActivity().startService(intent2);
					isPlaying = true;
					iv_music_play.setImageResource(R.drawable.pause1);
					replaying = true;
				}
				// 单曲循环
				else if (vdc.getType().equals(
						Constants.F_R_MUSIC_JUST_ONE_PLAY[0])) {

					iv_music_play_model
							.setImageResource(R.drawable.music_play_single);
					model = 3;
				}// 随机播放
				else if (vdc.getType().equals(
						Constants.F_R_MUSIC_RANDOM_PLAY[0])) {

					iv_music_play_model
							.setImageResource(R.drawable.music_play_random);
					model = 1;
				}
				// 顺序播放
				else if (vdc.getType()
						.equals(Constants.F_R_MUSIC_ORDER_PLAY[0])) {
					iv_music_play_model
							.setImageResource(R.drawable.music_play_order);
					model = 2;
				}
				// 播放列表
				else if (vdc.getType().equals(
						Constants.F_R_MUSIC_ALL_MUSIC_LIST[0])) {
					svd.setCommand(Constants.MAIN_MUSIC_COM);

					Log.i(TAG,
							intent.getStringExtra(Constants.MAIN_MUSIC_ACTION));
					CommonUtil.processBroadcast(getActivity(), svd);
				}
				// 上一首
				else if (vdc.getType().equals(
						Constants.F_R_MUSIC_LAST_MUSIC_PLAY[0])) {
					// 前一首
					int id = 0;
					if (model == 1) {
						id = MusicService.mid
								- (int) (Math.random() * lists.size() + 1);
					} else if (model == 2) {
						id = MusicService.mid - 1;
					} else if (model == 3) {
						id = MusicService.mid;
					}
					if (id > lists.size() - 1) {
						id = 0;
					} else if (id < 0) {
						id = lists.size() - 1;
					}
					DataMusicClass m = lists.get(id);
					tv_music_name.setText(m.getTitle());
					tv_music_singer.setText(m.getSinger());
					tv_music_end_time.setText(toTime((int) m.getTime()));
					iv_music_play.setImageResource(R.drawable.pause1);
					tv_music_start_time.setText("00:00");
					seekBar.setProgress(0);
					intent2.putExtra("play", "last");
					intent2.putExtra("id", id);
					getActivity().startService(intent2);
					isPlaying = true;
				}
				// 下一首
				else if (vdc.getType().equals(
						Constants.F_R_MUSIC_NEXT_MUSIC_PLAY[0])) {
					// 下一首
					int id = 0;
					if (model == 1) {
						id = MusicService.mid
								+ (int) (Math.random() * lists.size() + 1);
					} else if (model == 2) {
						id = MusicService.mid + 1;
					} else if (model == 3) {
						id = MusicService.mid;
					}
					if (id > lists.size() - 1) {
						id = 0;
					} else if (id < 0) {
						id = lists.size() - 1;
					}
					DataMusicClass m = lists.get(id);
					tv_music_name.setText(m.getTitle());
					tv_music_singer.setText(m.getSinger());
					tv_music_end_time.setText(toTime((int) m.getTime()));
					iv_music_play.setImageResource(R.drawable.pause1);
					tv_music_start_time.setText("00:00");
					seekBar.setProgress(0);
					intent2.putExtra("play", "next");
					intent2.putExtra("id", id);
					getActivity().startService(intent2);
					isPlaying = true;
				}
				// 停止播放
				else if (vdc.getType().equals(Constants.F_R_MUSIC_STOP_PLAY[0])) {
					intent2.putExtra("play", "pause");
					getActivity().startService(intent2);
					isPlaying = false;
					iv_music_play.setImageResource(R.drawable.play1);
					replaying = false;
				}
			}
			// 返回首页
			else if (action != null
					&& Constants.MAIN_RETURN_HOME_ACTION.equals(action)) {
				CommonUtil.retHomeFragment(getActivity());
			}
			// 电话界面导航
			else if (action != null
					&& Constants.MAIN_NAVI_ACTION.equals(action)) {

				svd = gson.fromJson(
						intent.getStringExtra(Constants.MAIN_NAVI_ACTION),
						SpeechVoiceData.class);

				svd.setCommand(Constants.MAIN_NAVI_COM);

				Log.i(TAG, intent.getStringExtra(Constants.MAIN_NAVI_ACTION));
				CommonUtil.processBroadcast(getActivity(), svd);
			}
			// 电话界面显示obd
			else if (action != null && Constants.MAIN_OBD_ACTION.equals(action)) {

				svd = gson.fromJson(
						intent.getStringExtra(Constants.MAIN_OBD_ACTION),
						SpeechVoiceData.class);
				vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

				svd.setCommand(Constants.MAIN_OBD_COM);
				svd.setValue(vdc.getValue());
				CommonUtil.processBroadcast(getActivity(), svd);
			}
			// 导航界面打电话
			else if (action != null
					&& Constants.MAIN_PHONE_ACTION.equals(action)) {

				svd = gson.fromJson(
						intent.getStringExtra(Constants.MAIN_PHONE_ACTION),
						SpeechVoiceData.class);
				vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

				svd.setCommand(Constants.MAIN_PHONE_COM);
				svd.setValue(vdc.getValue());
				CommonUtil.processBroadcast(getActivity(), svd);
			}
		}
	};

	/**
	 * 广播过滤器
	 * 
	 * @return
	 */
	private static IntentFilter makeNewMsgIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.COMMON_UTIL_ACTION);
		intentFilter.addAction(Constants.MAIN_MUSIC_ACTION);
		intentFilter.addAction(Constants.MAIN_RETURN_HOME_ACTION);
		intentFilter.addAction(Constants.MAIN_NAVI_ACTION);
		intentFilter.addAction(Constants.MAIN_PHONE_ACTION);
		intentFilter.addAction(Constants.MAIN_OBD_ACTION);

		return intentFilter;
	}

	private void init() {
		tv_music_name = (TextView) getActivity().findViewById(
				R.id.tv_music_name);
		tv_music_singer = (TextView) getActivity().findViewById(
				R.id.tv_music_singer);
		tv_music_start_time = (TextView) getActivity().findViewById(
				R.id.tv_music_start_time);
		tv_music_end_time = (TextView) getActivity().findViewById(
				R.id.tv_music_end_time);

		iv_music_last = (ImageView) getActivity().findViewById(
				R.id.iv_music_last);
		iv_music_next = (ImageView) getActivity().findViewById(
				R.id.iv_music_next);
		iv_music_play = (ImageView) getActivity().findViewById(
				R.id.iv_music_play);
		iv_music_play_model = (ImageView) getActivity().findViewById(
				R.id.iv_music_play_model);

		seekBar = (SeekBar) getActivity().findViewById(R.id.sb_music);

		lrcView = (LrcView) getActivity().findViewById(R.id.lv_show);

		iv_music_last.setOnClickListener(new MyListener());
		iv_music_next.setOnClickListener(new MyListener());
		iv_music_play.setOnClickListener(new MyListener());
		iv_music_play_model.setOnClickListener(new MyListener());

		// 电话状态监听
		TelephonyManager telephonyManager = (TelephonyManager) getActivity()
				.getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(new MobliePhoneStateListener(),
				PhoneStateListener.LISTEN_CALL_STATE);

		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				seekBar.setProgress(seekBar.getProgress());
				Intent intent = new Intent("com.example.frmusic.seekBar");
				intent.putExtra("seekBarPosition", seekBar.getProgress());
				getActivity().sendBroadcast(intent);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {

			}
		});
		myCompletionListner = new MyCompletionListner();
		IntentFilter filter = new IntentFilter("com.example.frmusic.completion");
		getActivity().registerReceiver(myCompletionListner, filter);

	}

	/**
	 * 电话状态的监听类
	 * 
	 * @author fengrui
	 * 
	 *         2015年8月10日
	 */
	private class MobliePhoneStateListener extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:// 无任何状态时
				Intent intent = new Intent(getActivity(), MusicService.class);
				intent.putExtra("play", "playing");
				intent.putExtra("id", choosedMusicId);
				getActivity().startService(intent);
				isPlaying = true;
				iv_music_play.setImageResource(R.drawable.pause1);
				replaying = true;
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:// 接听电话时

			case TelephonyManager.CALL_STATE_RINGING:// 电话进来时
				Intent intent2 = new Intent(getActivity(), MusicService.class);
				intent2.putExtra("play", "puase");
				getActivity().startService(intent2);
				isPlaying = false;
				iv_music_play.setImageResource(R.drawable.play1);
				replaying = false;
				break;
			default:
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}

	}

	@Override
	public void onStart() {
		gson = new Gson();
		// 获取service中发过来的信息
		receiver = new MyProgressBroadCastReceiver();
		IntentFilter filter = new IntentFilter("com.example.frmusic.progress");
		getActivity().registerReceiver(receiver, filter);
		// MainActivity中发来的信息
		// choosedMusicId = getActivity().getIntent().getIntExtra("id", 1);
		lists = MusicList.getMusicData(getActivity());

		Bundle bundle = getArguments();
		choosedMusicId = Integer.parseInt(bundle.getString("choosedMusicId"));// 获取列表界面选择的音乐id
		listTypeMusic = bundle.getString("listType");
		if (listTypeMusic != null) {
			lists = gson.fromJson(bundle.getString("listType"),
					new TypeToken<List<DataMusicClass>>() {
					}.getType());
		}
		// searchType = bundle.getString("listType");
		// if (searchType.contains(Constants.F_R_SEARCH_TYPE[0])) {// 歌手选择的音乐列表
		// lists = MusicList.getMusicBySinger(searchType.split("\\,")[1],
		// lists);
		// } else if (searchType.contains(Constants.F_R_SEARCH_TYPE[1])) {//
		// 歌曲选择的音乐列表
		// lists = MusicList.getMusicBySong(searchType.split("\\,")[1], lists);
		//
		// }
		// 再次播放replaying
		if (choosedMusicId == currentId) {
			DataMusicClass m = lists.get(choosedMusicId);
			tv_music_name.setText(m.getTitle());
			tv_music_singer.setText(m.getSinger());
			tv_music_end_time.setText(toTime((int) m.getTime()));
			Intent intent = new Intent(getActivity(), MusicService.class);
			intent.putExtra("play", "replaying");
			intent.putExtra("id", choosedMusicId);
			intent.putExtra("listType", gson.toJson(lists));
			getActivity().startService(intent);
			if (replaying == true) {
				iv_music_play.setImageResource(R.drawable.pause1);
				isPlaying = true;
			} else {
				iv_music_play.setImageResource(R.drawable.play1);
				isPlaying = false;
			}
		} else {
			DataMusicClass m = lists.get(choosedMusicId);
			tv_music_name.setText(m.getTitle());
			tv_music_singer.setText(m.getSinger());
			tv_music_end_time.setText(toTime((int) m.getTime()));
			iv_music_play.setImageResource(R.drawable.pause1);
			Intent intent = new Intent(getActivity(), MusicService.class);
			intent.putExtra("play", "play");
			intent.putExtra("id", choosedMusicId);
			intent.putExtra("listType", gson.toJson(lists));

			getActivity().startService(intent);
			isPlaying = true;
			replaying = true;
			currentId = choosedMusicId;
		}
		super.onStart();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		getActivity().registerReceiver(musicPlayReceiver,
				makeNewMsgIntentFilter());
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(musicPlayReceiver);
		super.onPause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(myCompletionListner);
		super.onDestroy();
	}

	private class MyListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (v == iv_music_last) {
				// 前一首
				int id = 0;
				if (model == 1) {
					id = MusicService.mid
							- (int) (Math.random() * lists.size() + 1);
				} else if (model == 2) {
					id = MusicService.mid - 1;
				} else if (model == 3) {
					id = MusicService.mid;
				}
				if (id > lists.size() - 1) {
					id = 0;
				} else if (id < 0) {
					id = lists.size() - 1;
				}
				DataMusicClass m = lists.get(id);
				tv_music_name.setText(m.getTitle());
				tv_music_singer.setText(m.getSinger());
				tv_music_end_time.setText(toTime((int) m.getTime()));
				iv_music_play.setImageResource(R.drawable.pause1);
				tv_music_start_time.setText("00:00");
				seekBar.setProgress(0);
				Intent intent = new Intent(getActivity(), MusicService.class);
				intent.putExtra("play", "last");
				intent.putExtra("id", id);
				getActivity().startService(intent);
				isPlaying = true;
			} else if (v == iv_music_play) {
				// 正在播放
				if (isPlaying) {
					Intent intent = new Intent(getActivity(),
							MusicService.class);
					intent.putExtra("play", "pause");
					intent.putExtra("id", choosedMusicId);
					getActivity().startService(intent);
					isPlaying = false;
					iv_music_play.setImageResource(R.drawable.play1);
					replaying = false;
				} else {
					Intent intent = new Intent(getActivity(),
							MusicService.class);
					intent.putExtra("play", "playing");
					intent.putExtra("id", choosedMusicId);
					getActivity().startService(intent);
					isPlaying = true;
					iv_music_play.setImageResource(R.drawable.pause1);
					replaying = true;
				}
			} else if (v == iv_music_next) {
				// 下一首
				int id = 0;
				if (model == 1) {
					id = MusicService.mid
							+ (int) (Math.random() * lists.size() + 1);
				} else if (model == 2) {
					id = MusicService.mid + 1;
				} else if (model == 3) {
					id = MusicService.mid;
				}
				if (id > lists.size() - 1) {
					id = 0;
				} else if (id < 0) {
					id = lists.size() - 1;
				}
				DataMusicClass m = lists.get(id);
				tv_music_name.setText(m.getTitle());
				tv_music_singer.setText(m.getSinger());
				tv_music_end_time.setText(toTime((int) m.getTime()));
				iv_music_play.setImageResource(R.drawable.pause1);
				tv_music_start_time.setText("00:00");
				seekBar.setProgress(0);
				Intent intent = new Intent(getActivity(), MusicService.class);
				intent.putExtra("play", "next");
				intent.putExtra("id", id);
				getActivity().startService(intent);
				isPlaying = true;
			} else if (v == iv_music_play_model) {
				if (model == 1) {
					iv_music_play_model
							.setImageResource(R.drawable.music_play_order);
					model = 2;
				} else if (model == 2) {
					iv_music_play_model
							.setImageResource(R.drawable.music_play_single);
					model = 3;
				} else if (model == 3) {
					iv_music_play_model
							.setImageResource(R.drawable.music_play_random);
					model = 1;
				}
			}
		}

	}

	public class MyProgressBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			int position = arg1.getIntExtra("position", 0);
			int total = arg1.getIntExtra("total", 1);
			if (total == 0) {
				total = 1;
			}
			int progress = position * 100 / total;
			tv_music_start_time.setText(toTime(position));
			seekBar.setProgress(progress);
			seekBar.invalidate();
		}

	}

	public class MyCompletionListner extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				DataMusicClass m = lists.get(MusicService.mid);
				tv_music_name.setText(m.getTitle());
				tv_music_singer.setText(m.getSinger());
				tv_music_end_time.setText(toTime((int) m.getTime()));
				iv_music_play.setImageResource(R.drawable.pause1);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public String toTime(int time) {
		time /= 1000;
		int minute = time / 60;
		int hour = minute / 60;
		int second = time % 60;
		minute %= 60;
		return String.format("%02d:%02d", minute, second);
	}

}
